#include <gtest/gtest.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>

#include "acceptor.h"
#include "eventloop.h"
#include "helper.h"

class DummyLoop : public EventLoop {
public:
    void updateChannel(Channel*)  {}
    void removeChannel(Channel*)  {}
};

TEST(AcceptorTest, HandleReadCallback) {
    DummyLoop loop;

    // 创建监听 Acceptor
    Acceptor acceptor(&loop, "127.0.0.1", 0);  // 端口为 0 自动分配
    acceptor.listen();

    int server_fd = AcceptorTestHelper::getListenFd(acceptor);  // 获取底层 socket fd

    // 获取系统自动分配的实际端口
    sockaddr_in addr {};
    socklen_t len = sizeof(addr);
    getsockname(server_fd, (sockaddr*)&addr, &len);

    // 设置回调标志
    bool callbackCalled = false;
    int accepted_fd = -1;

    acceptor.setNewConnectionCallback(
        [&](int connfd, const std::string& peer) {
            callbackCalled = true;
            accepted_fd = connfd;
        });

    // 模拟客户端连接
    int client_fd = ::socket(AF_INET, SOCK_STREAM, 0);
    ASSERT_GE(client_fd, 0);

    ASSERT_EQ(connect(client_fd, (sockaddr*)&addr, sizeof(addr)), 0);

    // 模拟有新连接到来
    AcceptorTestHelper::invokeHandleRead(acceptor); // 主动触发（正常情况下是 EventLoop 调用）

    ASSERT_TRUE(callbackCalled);
    ASSERT_GE(accepted_fd, 0);

    ::close(client_fd);
    ::close(accepted_fd);
}